

** get bounds for pop, treat as not subject to sampling error 
	scalar n_weeks = (`=mdy(12,22,2020)' - `=mdy(3,13,2020)')/7
	scalar n_pop = 6.6e6*n_weeks
	
	use health/test_daily_panel, clear
	egen week = cut(date), at(`=mdy(3,13,2020)'(7)`=mdy(12,22,2020)')
	collapse (max) positive tested, by(sid week)	
	
	
	sum positive 
	scalar n_pos = r(sum)
	sum tested
	scalar n_test = r(sum)
	scalar test_rate_pop = n_test / n_pop
	scalar conf_rate_pop = n_pos /n_pop
	scalar pos_rate_pop = n_pos / n_test

	di test_rate_pop 
	di conf_rate_pop
	di pos_rate_pop
	
** set up for intersection bounds 
** find confidence in tervals 
use tables/bounds_by_cause_bs, clear

gen ub_int_m = min(pos_rate, pos_rate_pop)
gen ub_int_i = ub_int_m
gen lb_int_m = conf_rate_pop
gen lb_int_i = max(pos_rate*test_rate, conf_rate_pop)

foreach v in ub_int_i ub_int_m lb_int_m lb_int_i {
	sort group `v'
	local p .025
	if "`v'" == "ub_int_i" | "`v'" == "ub_int_m" local p = .975
	local n = ceil(`p'*500)
	by group: gen `v'1 = `v'[`n']
}

by group: keep if _n==1
keep *1 group
tempfile ci 
save `ci'

** main estimates, intersection bounds, and confidence intervals
use tables/bounds_by_cause_bs if iter == 0, clear
gen ub_int_m0 = min(pos_rate, pos_rate_pop)
gen ub_int_i0 = ub_int_m
gen lb_int_m0 = conf_rate_pop
gen lb_int_i0 = max(pos_rate*test_rate, conf_rate_pop)
merge 1:1 group using `ci', assert(3) nogen

list group n test_rate *0
reshape long lb_int_i ub_int_i lb_int_m ub_int_m , i(group) j(ci)

list group n test_rate lb_int_i ub_int_i lb_int_m ub_int_m , sep(2)

foreach v in lb_int_i ub_int_i lb_int_m ub_int_m test_rate {
	gen s = string(`v', "%4.3f") 
	drop `v'
	rename s `v'
	if strpos("`v'", "lb") replace `v' = "[" + `v' + ", " 
	if strpos("`v'", "ub") replace `v' = `v' + "] & " 
	replace `v' = subinstr(`v', "[", "(", .) if ci
	replace `v' = subinstr(`v', "]", ")", .) if ci
}
replace test_rate = test_rate + " & "

gen ns= string(n,"%12.0fc") + " & " 
drop n
rename ns n

replace ub_int_i = subinstr(ub_int_i, "&", "\\", .)
replace ub_int_i = ub_int_i + "\\" if ci & group ~= "wound"

replace group = proper(subinstr(group, "_", " ", .)) + " & "
replace group = " & " if ci
replace test_rate = " & " if ci
replace n = " & " if ci


list group n test_rate  lb_int_m ub_int_m lb_int_i ub_int_i , noobs clean
outsheet group n test_rate lb_int_m ub_int_m lb_int_i ub_int_i using ///
	tables/groups_pool_time.tex, replace noquote nonames delimit(" ")
